package com.xpwu.secondary.rabbitmq.producer;

import com.xpwu.secondary.bo.CommonOrderBO;
import com.xpwu.secondary.enums.RabbitMqEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author admin
 * rabbitmq发送消息工具类
 */
@Component
@Slf4j
public class DirectMqSender implements RabbitTemplate.ConfirmCallback {

    @Value("${spring.rabbitmq.order.ttl}")
    private int ttl;

    @Resource(name = "rabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    @Autowired
    public DirectMqSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        log.info("confirm: " + correlationData.getId());
    }

    /**
     * 发送到 指定routekey的指定queue
     *
     * @param route
     * @param obj
     */
    public void sendRabbitmqDirect(RabbitMqEnum.RoutingEnum route, Object obj) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        log.info("send: " + correlationData.getId());
        this.rabbitTemplate.convertAndSend(RabbitMqEnum.Exchange.SECONDARY_CONTRACT_DIRECT.getCode(), route.getCode(), obj, correlationData);
    }

    public void sendTtlMessage(RabbitMqEnum.RoutingEnum route, String orderId) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        log.info("send ttl: " + correlationData.getId());
        log.info("ttl:" + ttl);
        this.rabbitTemplate.convertAndSend(RabbitMqEnum.Exchange.SECONDARY_ORDER_DEAD_LETTER_ECHANGE.getCode(), route.getCode(), orderId, message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            messageProperties.setContentEncoding("UTF-8");
            messageProperties.setExpiration(ttl + "");
            return message;
        }, correlationData);
    }
}
